/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2025-02-13
 * Time: 23:04
 */

package com.example.common.security;
import com.example.common.core.domain.R;
import com.example.common.core.enums.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
//import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */

// 对于其他微服务而言, GlobalExceptionHandler 是没有注入到指定微服务的 Spring 容器下的
// 因此也需要使用配置文件 org.springframework.boot.autoconfigure.AutoConfiguration.imports
@RestControllerAdvice
//@Slf4j
public class GlobalExceptionHandler
{
    /**
     * 请求⽅式不⽀持 POST 请求传入的是 GET 等其他请求时被捕获
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
// log.error("请求地址'{}',不⽀持'{}'请求", requestURI, e.getMethod());
        return R.fail(ResultCode.ERROR);
    }
    /**
     * 拦截运⾏时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
// log.error("请求地址'{}',发⽣异常.", requestURI, e);
        return R.fail(ResultCode.ERROR);
    }

    /**
     * 系统异常 -- 兜底捕获, 防止没有写入的异常
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
// log.error("请求地址'{}',发⽣异常.", requestURI, e);
        return R.fail(ResultCode.ERROR);
    }
}
